package com.bclz.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 堆外内存创建,操作系统不需要拷贝一次
 * eg: FileChannel
 */
public class MappedByteBufferExample {

    public static void main(String[] args) throws IOException {
        RandomAccessFile randomAccessFile=new RandomAccessFile("E:/test.txt","rw");
        FileChannel channel = randomAccessFile.getChannel();

        //第三个参数size表示多少个字节映射到内存
        //position-size个字节放到缓冲区
        //直接修改，不需要重新拷贝一次
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, (int) channel.size());
        //第0个字节
        mappedByteBuffer.put(0,(byte) 'X');
        channel.close();
        randomAccessFile.close();
    }

}
